package com.versita.utils;

import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil {
    private static SessionFactory sessionFactory = null;

    /**
     * Use the annotation in the cfg.xml to map the *.xml
     * @return
     */
    private static SessionFactory buildSessionFactory() {
        return buildSessionFactory(null,null);
    }

    /**
     * 
     * @param classes
     * @param configFile
     * @return
     */
    private static SessionFactory buildSessionFactory(List<Class> classes,
            String configFile) {
        AnnotationConfiguration configuration = new AnnotationConfiguration();

        if (classes != null) {
            for (Iterator<Class> i=classes.iterator(); i.hasNext(); ) {
                Class myclass = i.next();
                configuration.addAnnotatedClass(myclass);
            }
        }

        if (configFile != null) {
            configuration.configure(configFile);
        } else {
            configuration.configure();
        }

        new SchemaExport(configuration).create(true,true);

        sessionFactory = configuration.buildSessionFactory();
        return sessionFactory;
    }

    /**
     * This one is used in conjunction with bnd.xml.
     * @return
     */
    public static SessionFactory getSessionFactory() {
        return getSessionFactory(null, null);
    }

    /**
     * This one is used in conjunction with dynamic load.
     * i.e., configuration.addAnnotatedClass;
     * @param classes
     * @param configFile
     * @return
     */
    public static SessionFactory getSessionFactory(List<Class> classes, String configFile) {
        if (sessionFactory == null) {
            return buildSessionFactory(classes, configFile);
        } else {
            return sessionFactory;
        }
    }
}